PROJDIRS := includes .

SRCFILES := $(shell find $(PROJDIRS) -mindepth 1 -maxdepth 3 -name "*.c")
SRCFILESASM := $(shell find $(PROJDIRS) -mindepth 1 -maxdepth 3 -name "*.s")
HDRFILES := $(shell find $(PROJDIRS) -mindepth 1 -maxdepth 3 -name "*.h")
OBJFILES := $(patsubst %.c,%.o,$(SRCFILES))
OBJFILESASM := $(patsubst %.s,%.os,$(SRCFILESASM))
DEPFILES := $(patsubst %.c,%.d,$(SRCFILES))
ALLFILES := $(SRCFILES) $(HDRFILES) $(SRCFILESASM)

GCC := x86_64-pc-linux-gcc
LD := x86_64-pc-linux-ld -T linkKernel.ld
OBJCPY := x86_64-pc-linux-objcopy -I elf64-x86-64 -O binary
NASM := nasm -f elf64

.PHONY: all clean todolist

CFLAGS := -Wall -Wextra -ffreestanding -nostdlib -nostartfiles -nodefaultlibs -m64 -mcmodel=large -std=gnu99 -O0


all: kernel.bin

    kernel.bin: $(OBJFILES) $(OBJFILESASM) linkKernel.ld
			@$(LD) -o kernel.elf $?
			@$(OBJCPY) kernel.elf kernel.bin
			
clean:
	-@cp kernel.elf kernel.elf.old
	-@$(RM) $(wildcard $(OBJFILES) $(DEPFILES) $(OBJFILESASM) kernel.bin kernel.elf)

-include $(DEPFILES)

todolist:
			-@for file in $(ALLFILES); do fgrep -H -e TODO -e FIXME $$file; done; true

 %.o: %.c Makefile
			@$(GCC) $(CFLAGS) -MMD -MP -MT "$*.d" -I./includes -c $< -o $@

 %.os: %.s Makefile
			@$(NASM) -o $@ $<